var modal = document.querySelectorAll(".camera");
var cameraImg = document.querySelectorAll(".camera-img");
var warning = document.querySelector(".warning");
var shade = document.getElementById("shade");
var reportBtn = document.querySelector(".button-report");
var modal1 = document.getElementById("modal1");
var modal2 = document.getElementById("modal2");
var modal3 = document.getElementById("modal3");
var emClose = document.querySelector(".emphasis-close");
var moClose = document.querySelector(".monitor-close");
var staClose = document.querySelector(".statement-close");
var message = document.querySelector(".messageBox");
var previewRe = document.querySelector(".previewReport");
var generateRe = document.querySelector(".generateReport");
let cModal_title = document.querySelector(".monitor-title");
let ctitle = document.querySelectorAll(".camera-title");
let doorTitle = document.querySelector(".door_title");
let page_ul = document.querySelector(".pagination");
let resData = {};
let finish = false;
monitorCode = [];
var dioLoading = LoadingSingleton.getInstance();

function getDoorMonitor(data) {
  $.ajax({
    url: "/large-screen/region/selectMonitorsByRegionV3",
    type: "GET",
    crossDomain: true,
    dataType: "json",
    async: false,
    data: data,
    success: function (res) {
      // console.log(res);
      resData = res.data;
      // 获取门的indexCode
      for (let i = 0; i < resData.child[0].voList.length; i++) {
        monitorCode.push(resData.child[0].voList[i].monitorIndexCode);
      }
      // console.log(monitorCode);
      // initPlugin();
      setTimeout(() => {
        monitorPreview();
      }, 1000);
    },
    error: function (xhr, status) {
      console.log(status);
    },
  });
}

// 点击摄像头出弹窗
for (let i = 0; i < modal.length; i++) {
  modal[i].onclick = (e) => {
    monitorCode = [];
    cameraImg[i].setAttribute("src", "/assets/编组 19.png");
    shade.classList.remove("hide");
    modal1.classList.remove("hide");
    cModal_title.innerText = ctitle[i].innerText;
    // console.log(regionPaths[i]);
    initPlugin();
    getDoorMonitor({
      regionIndexCode: regionPaths[i],
      pageNum: 1,
    });
    doorTitle.innerText = resData.child[0].regionName;
    // 创建分页
    for (let i = 0; i < resData.total; i++) {
      var page_li = document.createElement("li");
      page_li.innerText = `${i + 1}`;
      page_ul.appendChild(page_li);
    }
    var pages = document.querySelectorAll(".pagination>li");
    pages[0].classList.add("page_active");
    for (let k = 0; k < pages.length; k++) {
      pages[k].onclick = () => {
        oWebControl.JS_DestroyWnd();
        monitorCode = [];
        for (let j = 0; j < pages.length; j++) {
          pages[j].classList.remove("page_active");
        }
        pages[k].classList.add("page_active");
        initPlugin();
        getDoorMonitor({
          regionIndexCode: regionPaths[i],
          pageNum: k + 1,
        });
        doorTitle.innerText = resData.child[0].regionName;
        $(".noMon").hide();
      };
    }
  };
}

warning.onclick = () => {
  shade.classList.remove("hide");
  modal2.classList.remove("hide");
};

shade.onclick = () => {
  clearDateRange();
  shade.classList.add("hide");
  modal1.classList.add("hide");
  modal2.classList.add("hide");
  modal3.classList.add("hide");
  message.classList.remove("animated");
  for (let i = 0; i < cameraImg.length; i++) {
    cameraImg[i].setAttribute("src", "/assets/编组 19-2.png");
  }
  // 弹窗关闭，清除page_li
  page_ul.innerHTML = "";
  // 弹窗关闭，插件窗口隐藏
  // HideWnd();
  $(".noMon").hide();
  oWebControl.JS_DestroyWnd();
};

emClose.onclick = () => {
  shade.classList.add("hide");
  modal2.classList.add("hide");
};
moClose.onclick = () => {
  shade.classList.add("hide");
  modal1.classList.add("hide");
  for (let i = 0; i < cameraImg.length; i++) {
    cameraImg[i].setAttribute("src", "/assets/编组 19-2.png");
  }
  $(".noMon").hide();
  // 弹窗关闭，清除page_li
  page_ul.innerHTML = "";
  // 弹窗关闭，插件窗口隐藏
  // HideWnd();
  oWebControl.JS_DestroyWnd();
  /* // 弹窗关闭，停止预览
  oWebControl.JS_RequestInterface({
    funcName: "stopAllPreview",
  }); */
};
staClose.onclick = () => {
  shade.classList.add("hide");
  modal3.classList.add("hide");
  message.classList.remove("animated");
  clearDateRange();
};
reportBtn.onclick = () => {
  shade.classList.remove("hide");
  modal3.classList.remove("hide");
  clearDateRange();
};

function generateReport() {
  var startDate = document.getElementById("start-date").value;
  var endDate = document.getElementById("end-date").value;
  message.classList.remove("animated");
  message.classList.remove("success");
  message.classList.remove("fail");
  if (startDate && endDate) {
    dioLoading.showLoading();
    $.ajax({
      url: "/large-screen/analyze/create",
      type: "POST",
      dataType: "json",
      contentType: "application/json; charset=utf-8",
      data: JSON.stringify({
        startTime: document.getElementById("start-date").value,
        endTime: document.getElementById("end-date").value,
      }),
      success: function (res) {
        dioLoading.hideLoading();
        if (res.code == 200) {
          finish = true;
          previewRe.classList.add("getSuccess");
          generateRe.classList.add("getSuccess");
          message.innerText = "生成成功!";
          message.classList.add("animated");
          message.classList.add("success");
          setTimeout(() => {
            message.classList.remove("animated");
            message.classList.remove("success");
          }, 2000);
        } else {
          message.innerText = res.message;
          message.classList.add("animated");
          message.classList.add("fail");
          setTimeout(() => {
            message.classList.remove("animated");
            message.classList.remove("fail");
          }, 2000);
        }
      },
      error: function (xhr, status) {
        dioLoading.hideLoading();
        console.log(status);
        message.innerText = "请求超时!";
        message.classList.add("animated");
        message.classList.add("fail");
        setTimeout(() => {
          message.classList.remove("animated");
          message.classList.remove("fail");
        }, 2000);
      },
    });
  } else {
    message.innerText = "时间不能为空!";
    message.classList.add("animated");
    message.classList.add("fail");
    setTimeout(() => {
      message.classList.remove("animated");
      message.classList.remove("fail");
    }, 2000);
  }
}

// 预览报表
function previewReport() {
  if (!finish) return;
  window.open("http://192.168.0.142:8076/");
  // window.location.href = "http://192.168.0.142:8076/";
}

// 生成报表
function downloadReport() {
  if (!finish) return;
  dioLoading.showLoading();
  $.ajax({
    url: "/large-screen/analyze/analysis-report",
    type: "GET",
    contentType: "application/octet-stream",
    success: function (res) {
      dioLoading.hideLoading();
      if (res.code === "500") {
        message.innerText = "报表生成失败!";
        message.classList.add("animated");
        message.classList.add("fail");
        setTimeout(() => {
          message.classList.remove("animated");
          message.classList.remove("fail");
        }, 2000);
        return;
      }
      /* message.innerText = "报表生成成功!";
      message.classList.add("animated");
      message.classList.add("success");
      setTimeout(() => {
        message.classList.remove("animated");
        message.classList.remove("success");
      }, 2000); */
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = res.data;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); //下载完成移除元素
    },
  });
}

// 验证日期范围的函数
function validateDateRange() {
  // 获取开始日期和结束日期的值，并将它们转换为Date对象
  var startDate = new Date(document.getElementById("start-date").value);
  var endDate = new Date(document.getElementById("end-date").value);
  // 检查开始日期和结束日期是否有效（不是NaN）
  var isStartDateValid = !isNaN(startDate.getTime());
  var isEndDateValid = !isNaN(endDate.getTime());
  // 如果开始日期和结束日期都有效，则进行下一步验证
  if (isStartDateValid && isEndDateValid) {
    // 检查结束日期是否早于开始日期，如果是，则弹出警告并清空结束日期输入框
    if (endDate < startDate) {
      message.innerText = "结束日期不能早于开始日期!";
      message.classList.add("animated");
      message.classList.add("fail");
      setTimeout(() => {
        message.classList.remove("animated");
        message.classList.remove("fail");
      }, 2000);
      document.getElementById("end-date").value = "";
    } else {
      // 如果结束日期不早于开始日期，则显示日期范围
    }
  } else {
  }
}

// 清除日期范围的函数
function clearDateRange() {
  // 清空开始日期和结束日期输入框的值
  document.getElementById("start-date").value = "";
  document.getElementById("end-date").value = "";
  previewRe.classList.remove("getSuccess");
  generateRe.classList.remove("getSuccess");
  finish = false;
}
